#! /usr/bin/env python
#coding=utf-8

import os
import pickle
import time

from ljnetworkapi import LJUserSession
from ljvisualize import LJVisualizer

LJUserName = "xoranger"
SCAN_DEPTH = 3

if not os.path.exists(LJUserName):
    
    # start collecting data
    session = LJUserSession(LJUserName, "")
    session.setVerbose(False)            # be verbose!
    session.setThreadsCount(2)
    print "Traversing all the friends of LJ user " + LJUserName + " ( max depth = " + str(SCAN_DEPTH) + " ), this can take a long time... \n", 
    stat = LJUserSession.getStatDataStruct()
    output = session.scanAllFriends(SCAN_DEPTH, stat, True)
    print "Done"

    print "Saving to file... ",
    # save output file (serialized)
    f = open(LJUserName, "wb")
    pickle.dump(output, f, pickle.HIGHEST_PROTOCOL)
    f.close()
    
    # save output file (human readable)
    """
    f = open(LJUserName + ".txt", "wt")
    tmp = output.toHR()
    for item in tmp:
        f.write(str(item) + '\n')
    f.close()
    """
    print "Ok"

    stat.showStats()

else:
    
    # run visualizer with the collected data
    print "Reading data, please wait...", 
    f = open(LJUserName, "rb")
    output = pickle.load(f)
    f.close()
    print "Ok"
    
    print "Preparing...",
    visualizer = LJVisualizer(output)
    visualizer.initPyGame()
    print "Ok"
    
    while(True):
        # render loop        
        visualizer.update()
        visualizer.paint()
        # yield
        time.sleep(0)
